<template>
  <div class="login-bg">
    <div class="login-container">
      <div class="login-title">招聘平台登录</div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        class="login-form"
        @submit.prevent
      >
        <el-form-item prop="username">
          <el-input
            v-model="ruleForm.username"
            placeholder="用户名"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
            size="large"
            type="password"
          />
        </el-form-item>

        <el-alert
          v-if="errorMessage"
          :title="errorMessage"
          type="error"
          show-icon
          style="margin-bottom: 20px"
          @close="errorMessage = ''"
        />

        <el-form-item class="button-group">
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            @click="submitForm(ruleFormRef)"
            :loading="loading"
            auto-insert-space
            style="flex: 1; margin-right: 10px"
          >
            登录
          </el-button>
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            @click="register"
            auto-insert-space
            style="flex: 1"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getLoginByUsername } from '@/api/login.ts'
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { setAuthStatus } from '@/utils/auth'
import { useRoleStore } from '../stores/role'
import { useAuthStore } from '../stores/auth'
import { showCustomMessage } from '../utils/message'

const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const loading = ref(false)
const errorMessage = ref('')
const roleStore = useRoleStore()
const authStore = useAuthStore()

interface RuleForm {
  username: string
  password: string
}

const ruleForm = reactive<RuleForm>({
  username: '',
  password: '',
})

const rules = reactive<FormRules<RuleForm>>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  try {
    loading.value = true
    errorMessage.value = ''
    await formEl.validate()
    await login()
  } catch (error) {
    console.log('表单验证失败', error)
  } finally {
    loading.value = false
  }
}

// 获取角色显示名称
const getRoleDisplayName = (role: string) => {
  const roleNames = {
    user: '用户界面',
    company: '企业界面',
    admin: '管理员界面',
  }
  return roleNames[role as keyof typeof roleNames] || '用户界面'
}

// 初始化角色和认证
onMounted(() => {
  roleStore.initRole()
  authStore.initAuth()
})
const login = async () => {
  try {
    const res = await getLoginByUsername(ruleForm.username)

    console.log('登录结果:', res.data)
    const { role } = res.data
    if (ruleForm.password === res.data.password) {
      // 存取用户名
      setAuthStatus(true, ruleForm.username)
      handleRouteByRole(role)
      // router.push('/home')
    } else {
      errorMessage.value = '用户名或密码错误'
    }
  } catch (error) {
    console.error('登录失败:', error)
    errorMessage.value = '用户名或密码错误'
  }
}

const register = () => {
  router.push('/register')
}

const handleRouteByRole = async (role) => {
  let roleValue = 'user'
  if (role == 2) {
    // 管理员
    roleValue = 'admin'
    router.push('/admin')
  } else if (role == 1) {
    // 企业
    roleValue = 'company'
    router.push('/company')
  } else if (role == 0) {
    // 用户
    roleValue = 'user'
    router.push('/user')
  }
  roleStore.setRole(roleValue)
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
  padding: 48px 36px 36px 36px;
  min-width: 340px;
  width: 360px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-title {
  font-size: 26px;
  font-weight: bold;
  color: #333;
  margin-bottom: 32px;
  letter-spacing: 2px;
}
.login-form {
  width: 100%;
}
.login-btn {
  width: 100%;
  font-size: 16px;
  letter-spacing: 2px;
}
</style>
